﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WP7Chess
{
    public partial class PlayerSelector : UserControl
    {
        private int selectedPlayer;
        private bool isUnchecking = false;

        public event EventHandler SelectionChanged;

        public PlayerSelector()
        {
            InitializeComponent();

            string[] players = this.Players;
            for (int i = 0; i < players.Length; i++)
            {
                ColumnDefinition column = new ColumnDefinition();
                column.Width = new GridLength(1.0 / players.Length, GridUnitType.Star);
                this.LayoutRoot.ColumnDefinitions.Add(column);

                CheckBox toggleButton = new CheckBox();
                Grid.SetColumn(toggleButton, i);
                toggleButton.Content = players[i];
                toggleButton.Checked += this.OnToggleButtonChecked;
                toggleButton.Unchecked += this.OnToggleButtonUnchecked;
                this.LayoutRoot.Children.Add(toggleButton);
            }
        }


        public string[] Players
        {
            get { return new string[] { "Human", "C#", "JS" }; }
        }

        public int SelectedPlayer
        {
            get { return this.selectedPlayer; }
            set
            {
                this.selectedPlayer = value;
                ((CheckBox)this.LayoutRoot.Children[value]).IsChecked = true;
            }
        }

        private void OnToggleButtonChecked(object sender, RoutedEventArgs e)
        {
            this.isUnchecking = true;
            foreach (CheckBox button in this.LayoutRoot.Children)
            {
                if (button == sender)
                {
                    this.selectedPlayer = this.LayoutRoot.Children.IndexOf(button);
                    if (this.SelectionChanged != null)
                    {
                        this.SelectionChanged(this, EventArgs.Empty);
                    }
                }
                else
                {
                    button.IsChecked = false;
                }
            }
            this.isUnchecking = false;
        }

        private void OnToggleButtonUnchecked(object sender, RoutedEventArgs e)
        {
            if (!this.isUnchecking)
                ((CheckBox)sender).IsChecked = true;
        }
    }
}
